package com.atguigu.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.app.func.MyAsyncJoinFunction;
import com.atguigu.bean.TestCourseBean;
import com.atguigu.util.ClickHouseUtil;
import com.atguigu.util.DateFormatUtil;
import com.atguigu.util.KafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

public class DwsTestCourseCount {
    public static void main(String[] args) throws Exception {
        // TODO 1 环境准备
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        
        // TODO 2 设置状态后端
        /*
        env.enableCheckpointing(5 * 60 * 1000L, CheckpointingMode.EXACTLY_ONCE );
        env.getCheckpointConfig().setCheckpointTimeout( 3 * 60 * 1000L );
        env.getCheckpointConfig().setMaxConcurrentCheckpoints(2);
        env.setStateBackend(new HashMapStateBackend());
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");
        System.setProperty("HADOOP_USER_NAME", "atguigu");
         */
        
        //TODO 3 从dwd_test_exam_paper获取数据
        String dwdTestExamPaper = "dwd_test_exam_paper";
        String groupId = "dws_test_course_count";
        DataStreamSource<String> dataStreamSource = env.addSource(KafkaUtil.getFlinkKafkaConsumer(dwdTestExamPaper, groupId));

        //TODO 4 过滤脏数据及空数据,并转换对象
        SingleOutputStreamOperator<JSONObject> jsonObjStream = dataStreamSource.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                if (value != null && !"".equals(value) && !"null".equals(value)) {
                    JSONObject jsonObject = JSON.parseObject(value);
                    out.collect(jsonObject);
                }
            }
        });
        SingleOutputStreamOperator<TestCourseBean> beanStream = jsonObjStream
                .keyBy(value -> value.getString("id"))
                .process(new KeyedProcessFunction<String, JSONObject, TestCourseBean>() {
                    ValueState<JSONObject> lastVisitState = null;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        ValueStateDescriptor<JSONObject> lastVisitDescriptor = new ValueStateDescriptor<>("lastVisit", JSONObject.class);
                        lastVisitDescriptor.enableTimeToLive(StateTtlConfig.newBuilder(org.apache.flink.api.common.time.Time.days(1L)).build());
                        lastVisitState = getRuntimeContext().getState(lastVisitDescriptor);
                    }

                    @Override
                    public void processElement(JSONObject value, Context ctx, Collector<TestCourseBean> out) throws Exception {
                        JSONObject lastVisit = lastVisitState.value();
                        if (lastVisit == null) {
                            ctx.timerService().registerProcessingTimeTimer(System.currentTimeMillis() + 5000L);
                            lastVisitState.update(value);
                        } else {
                            if (lastVisit.getLong("rt") < value.getLong("rt")) {
                                lastVisitState.update(value);
                            }
                        }
                    }

                    @Override
                    public void onTimer(long timestamp, OnTimerContext ctx, Collector<TestCourseBean> out) throws Exception {
                        JSONObject value = lastVisitState.value();
                        out.collect(TestCourseBean.builder()
                                .courseId(value.getString("course_id"))
                                .durationCt(value.getLong("duration_sec"))
                                .scoreCt(value.getDouble("score"))
                                .userCt(1L)
                                .ts(value.getLong("ts") * 1000L)
                                .build());
                    }
                });
        //TODO 5 设置水位线开窗聚合
        SingleOutputStreamOperator<TestCourseBean> reduceStream = beanStream.assignTimestampsAndWatermarks(WatermarkStrategy
                .<TestCourseBean>forBoundedOutOfOrderness(Duration.ofSeconds(2L))
                .withTimestampAssigner(new SerializableTimestampAssigner<TestCourseBean>() {
                    @Override
                    public long extractTimestamp(TestCourseBean element, long recordTimestamp) {
                        return element.getTs();
                    }
                })
        ).keyBy(value -> value.getCourseId())
                .window(TumblingEventTimeWindows.of(Time.seconds(10L)))
                .reduce(new ReduceFunction<TestCourseBean>() {
                    @Override
                    public TestCourseBean reduce(TestCourseBean value1, TestCourseBean value2) throws Exception {
                        value1.setUserCt(value1.getUserCt() + value2.getUserCt());
                        value1.setScoreCt(value1.getScoreCt() + value2.getScoreCt());
                        value1.setDurationCt(value1.getDurationCt() + value2.getDurationCt());
                        return value1;
                    }
                }, new WindowFunction<TestCourseBean, TestCourseBean, String, TimeWindow>() {
                    @Override
                    public void apply(String s, TimeWindow window, Iterable<TestCourseBean> input, Collector<TestCourseBean> out) throws Exception {
                        TestCourseBean next = input.iterator().next();
                        next.setStt(DateFormatUtil.toYmdHms(window.getStart()));
                        next.setEdt(DateFormatUtil.toYmdHms(window.getEnd()));
                        next.setTs(System.currentTimeMillis());
                        out.collect(next);
                    }
                });
        //TODO 6 维度关联
        SingleOutputStreamOperator<TestCourseBean> resultStream = AsyncDataStream.unorderedWait(reduceStream, new MyAsyncJoinFunction<TestCourseBean>("DIM_COURSE_INFO") {
            @Override
            public String getKey(TestCourseBean input) {
                return input.getCourseId();
            }

            @Override
            public TestCourseBean join(TestCourseBean input, JSONObject jsonObject) {
                String courseName = jsonObject.getString("courseName");
                input.setCourseTitle(courseName);
                return input;
            }
        }, 60L, TimeUnit.SECONDS);
        resultStream.print();
        //TODO 7 写出到clickhouse
        resultStream.addSink(ClickHouseUtil.getClickHouseSink("insert into  dws_test_course_count_window values(?,?,?,?,?,?,?,?)"));
        //TODO 8 任务启动
        env.execute(groupId);
    }
}
